package com.wms.controller;

import cn.hutool.jwt.JWTUtil;
import com.wms.bean.ResultBean;
import com.wms.core.R;
import com.wms.dto.LoginDto;
import com.wms.entity.User;
import com.wms.exception.V;
import com.wms.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api")
public class UserController {
    //@Value("${token.secret}")
    //String secret;

    @Autowired
    UserService userService;
    public ResultBean login(@Validated @RequestBody LoginDto loginDto, BindingResult result){
        V.validate(result);
        //根据手机号查询用户
        User user = userService.queryByMobile(loginDto.getMobile());
        if (user == null){
            return R.fail("用户不存在");
        }
        //判断密码是否正确
        //对用户输入的密码加密
        String tmp = DigestUtils.md5DigestAsHex(loginDto.getMobile().getBytes());
        if (!tmp.equals(loginDto.getPassword())){
            return R.fail("账号或密码错误");
        }
        //判断登陆状态
        if(user.getStatus()==0){
            return R.fail("用户已被禁用");
        }

        //执行到这里生成token
        Map payload = new HashMap<>();
        payload.put("id",user.getId());
        payload.put("mobile",user.getMobile());
        payload.put("name",user.getName());
        //String token = JWTUtil.createToken(payload,secret.getBytes());
        //payload.put("token",token);
        return R.success("登录成功");
    }
}
